package com.zb.job;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.zb.constant.WorkConstant;
import com.zb.entity.*;
import com.zb.service.*;
import com.zb.service.impl.ZjWorkDispatchNetworkServiceImpl;
import com.zb.service.impl.ZjWorkOrderServiceImpl;
import com.zb.utils.SpringContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.UUID;

/**
 * @Author WEN
 * @Date 2025/7/8 0008
 **/
@Slf4j
public class NetworkReceiveTimeoutJob implements Job {

    public NetworkReceiveTimeoutJob() {}

    public NetworkReceiveTimeoutJob(Long custAccId, Long workDispatchNetworkId) throws SchedulerException {
        log.info("创建网点超时未接单定时任务:{}", LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));

        ZjWorkSetService workSetService = SpringContextUtil.getBean(ZjWorkSetService.class);
        if (workSetService == null){
            log.error("获取工单设置服务失败");
            return;
        }

        ZjWorkSet workSet = workSetService.getById(custAccId);
        log.info("获取工单设置结果：{}", workSet);
        if (workSet == null)return;

        Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();

        JobDetail jobDetail = JobBuilder.newJob(NetworkReceiveTimeoutJob.class)
                .withIdentity("dispatchNetworkTimeoutJob" + UUID.randomUUID())
                .usingJobData("workDispatchNetworkId", workDispatchNetworkId)
                .build();

        Trigger trigger = TriggerBuilder.newTrigger()
                .startAt(DateBuilder.futureDate(workSet.getNetworkReceiveTimeout(), DateBuilder.IntervalUnit.HOUR))
                .build();

        scheduler.scheduleJob(jobDetail, trigger);

        scheduler.start();
    }

    @Override
    @Transactional
    public void execute(JobExecutionContext jobExecutionContext){
        log.info("服务商超时未接单任务执行:{}", LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));

        JobDataMap jobDataMap = jobExecutionContext.getJobDetail().getJobDataMap();
        long workDispatchNetworkId = jobDataMap.getLong("workDispatchNetworkId");
        log.info("工单分派网点id：{}", workDispatchNetworkId);

        ZjWorkDispatchNetworkService workDispatchNetworkService = SpringContextUtil.getBean(ZjWorkDispatchNetworkServiceImpl.class);
        if (workDispatchNetworkService == null){
            log.error("获取工单分配网点服务失败"); return;
        }

        ZjWorkDispatchNetwork workDispatchNetwork = workDispatchNetworkService.getById(workDispatchNetworkId);
        log.info("获取工单分配网点结果：{}", workDispatchNetwork);
        if (workDispatchNetwork == null || workDispatchNetwork.getStatus() != WorkConstant.DISPATCH_NETWORK_STATUS_1) return;

        ZjWorkOrderService workOrderService = SpringContextUtil.getBean(ZjWorkOrderServiceImpl.class);
        if (workOrderService == null){
            log.error("获取工单服务失败"); return;
        }

        ZjWorkOrder workOrder = workOrderService.getById(workDispatchNetwork.getWorkId());
        log.info("获取工单结果：{}", workOrder);
        if (workOrder == null || workOrder.getStatus() != WorkConstant.WORK_STATUS_2) return;

        log.info("修改为拒绝接单");
        workDispatchNetwork.setStatus(WorkConstant.DISPATCH_NETWORK_STATUS_8);
        workDispatchNetworkService.updateById(workDispatchNetwork);

        log.info("修改为待派单");
        workOrder.setStatus(WorkConstant.WORK_STATUS_1);
        workOrderService.updateById(workOrder);

        ZjWorkLogService workLogService = SpringContextUtil.getBean(ZjWorkLogService.class);
        if (workLogService == null){
            log.error("获取工单日志服务失败");
            return;
        }

        ZjNetworkService networkService = SpringContextUtil.getBean(ZjNetworkService.class);
        if(networkService == null){
            log.error("获取网点服务失败");
            return;
        }

        ZjNetwork network = networkService.getById(workDispatchNetwork.getNetworkId());
        if (network == null) return;

        log.info("记录工单日志");
        ZjWorkLog workLog = new ZjWorkLog();
        workLog.setId(IdWorker.getId());
        workLog.setCustAccId(workOrder.getCustAccId());
        workLog.setWorkId(workOrder.getId());
        workLog.setType(6);
        workLog.setName("");
        workLog.setCreateEmp("");
        workLog.setEvent("服务商超时未接单");
        workLog.setContent("服务商【" + network.getName() +"】超时未接单，待重新分派服务商");
        workLogService.save(workLog, new ArrayList<>());
    }
}
